/**
 * 
 */
package jmine.tec.utils.xml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * Classe utilitaria para converter para {@link Document}
 * 
 * @author takeshi
 */
public class XMLBuilder {

    private final DocumentBuilder builder;

    /**
     * 
     */
    public XMLBuilder() {
        try {
            DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
            this.builder = builderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    /**
     * Le um documento a partir de uma string
     * 
     * @param xmlAsString String representation of XML file. Must be in UTF-8
     * @return {@link Document}
     */
    public Document readDocumentUnchecked(final String xmlAsString) {
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(xmlAsString.getBytes("utf-8"));
            return this.builder.parse(bis);
        } catch (UnsupportedEncodingException e) {
            throw new UnrecoverableError();
        } catch (SAXException e) {
            throw new IllegalArgumentException(e);
        } catch (IOException e) {
            throw new UnrecoverableError();
        }
    }

    /**
     * @author takeshi
     */
    private static final class UnrecoverableError extends Error {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        /**
         * Ignores
         * 
         * @return Throwable
         * @see java.lang.Throwable#fillInStackTrace()
         */
        @Override
        public Throwable fillInStackTrace() {
            return this;
        }

    }

}
